<template>
  <t-dialog width="80%" header="新增护理计划" :visible.sync="visiable" :confirmOnEnter="true" @close="closeAddDialog"
    @confirm="saveProject">
    <t-space direction="vertical" style="width: 100%">
      <!-- rule:绑定表单每一项的校验规则 -->
      <t-form :data="addFormData" labelWidth="calc(8em + 24px)" layout="vertical" :rules="addFormRule"
        ref="nusrong_plan_form" @reset="onReset" @submit="saveProjectToDB">
        <t-form-item label="护理计划名称" name="planName">
          <t-input v-model="addFormData.planName" placeholder="请输入护理计划名称"></t-input>
        </t-form-item>
        <t-form-item label="排序" name="sortNo">
          <t-input v-model="addFormData.sortNo" type="number" placeholder="请输入护理计划排序"></t-input>
        </t-form-item>
        <t-form-item label="状态" name="status">
          <t-radio-group v-model="addFormData.status">
            <t-radio :checked="true" value="1">启用</t-radio>
            <t-radio :checked="false" value="0">禁用</t-radio>
          </t-radio-group>
        </t-form-item>
        <t-form-item label="选择护理项目" name="projects">
          <!-- 表格显示护理项目列表 -->
          <t-table bordered row-key="index" :data="projectList" :columns="add_columns">
            <template #execute_cycle="{ row }">
              <span style="color:red;display: inline-block;" v-if="row.noFinish">*</span>
              <t-select v-model="row.executeCycle" width="200px" id="cycle">
                <t-option key="apple" label="天" value="0" />
                <t-option key="orange" label="周" value="1" />
                <t-option key="banana" label="月" value="2" />
              </t-select>
            </template>
            <template #execute_frequency="{ row }">
              <span style="color:red;display: inline-block;" v-if="row.noFinish">*</span>
              <t-input type="number" v-model="row.executeFrequency" placeholder="请输入执行频次"></t-input>
            </template>
            <template #execute_time="{ row }">
              <span style="color:red;display: inline-block;" v-if="row.noFinish">*</span>
              <t-time-picker v-model="row.executeTime" format="HH:mm" />
            </template>
          </t-table>
        </t-form-item>
      </t-form>
    </t-space>
  </t-dialog>
</template>
<script setup lang="js">
import { ref, onMounted, watch } from 'vue'
import add_columns from '../add_columns'
import { getList } from '@/api/nursing_project_api'
import { MessagePlugin } from 'tdesign-vue-next'
import { saveNursingPlan } from '@/api/nursing_plan_api'
const props = defineProps(['visiable'])
const emit = defineEmits(['closeAddDialog', 'refresh'])

const addFormData = ref({})
const projectList = ref([])
// 表单对象
const nusrong_plan_form = ref(null)


const closeAddDialog = () => {
  emit('closeAddDialog')
}

// 只执行一次
onMounted(() => {
  loadList({ pageSize: 100 })
})

// 校验规则
const addFormRule = ref({
  planName: [
    {
      required: true,
      message: "护理计划名称是必填项"
    }
  ],
  sortNo: [
    {
      required: true,
      message: "排序号是必填项"
    }
  ],
  status: [
    {
      required: true,
      message: "状态是必填项"
    }
  ]
})

// 加载项目列表
const loadList = async (params) => {
  const resp = await getList(params)
  console.log("列表数据：", resp);

  projectList.value = resp.records

  // 添加表格项目中验证标志
  for (let index = 0; index < projectList.value.length; index++) {
    const element = projectList.value[index];
    element.noFinish = false
  }
}

// 点击对话框的确定按钮，手动触发表单的提交方法
const saveProject = () => {
  nusrong_plan_form.value.submit()
}
// 保存护理计划 
const saveProjectToDB = ({ validateResult, firstError }) => {
  // 统计不完整的行数
  let count = 0
  // 循环检查
  // 一行数据只要有一个填写了，其它两个必须填写，标志打开
  for (let index = 0; index < projectList.value.length; index++) {
    let element = projectList.value[index];

    // 未填写的字段值是undefined,长度是9,3个都不填，长度是27
    // 3个都填写，最少长度是7，最大是8
    let length = (element.executeCycle + "").length + (element.executeFrequency + "").length + (element.executeTime + "").length

    if (length != 7 && length != 8 && length != 27) {
      element.noFinish = true
      count++
    }
  }

  // true表示校验通过
  if (validateResult === true && count === 0) {
    let listData = []
    // 填写了数据的表格行才提交
    for (let index = 0; index < projectList.value.length; index++) {
      let element = projectList.value[index];
      if ((element.executeCycle + "").length > 0 && (element.executeCycle + "").length != 9) {
        listData.push(element)
      }
    }

    addFormData.value.nursingProjectPlans = listData

    console.log("提交的数据：", addFormData.value);

    save(addFormData.value)

  } else {
    if (firstError) {
      MessagePlugin.warning(firstError);
    }
    if (count > 0) {
      MessagePlugin.warning(count + "行表单数据不完整，查看表格的红色*号标记")
    }
  }
}

const save = async (obj) => {
  await saveNursingPlan(obj)

  // 关闭对话框
  emit('closeAddDialog')
  // 清空数据

  // 刷新列表
  emit('refresh')
}


</script>

<style lang="css" scoped>
#cycle {
  display: inline-block !important;
}
</style>